package com.anysoft.util;

import com.google.re2j.Matcher;
import com.google.re2j.Pattern;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 提供内置日期格式化变量的Properties
 */
public class DateProperties extends DefaultProperties {
    protected long timestamp = 0;
    protected static Pattern pattern = Pattern.compile("tf\\((.+)\\)");
    protected static ThreadLocal<SimpleDateFormat> factory = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat();
        }
    };

    public DateProperties(long tt, Properties p) {
        super("tt", p);
        this.timestamp = tt <= 0 ? System.currentTimeMillis() : tt;
    }

    @Override
    protected String _GetValue(String _name) {
        if (_name.equals("tt")) {
            return String.valueOf(timestamp);
        }
        Matcher matcher = pattern.matcher(_name);
        if (matcher.find()) {
            SimpleDateFormat formatter = factory.get();
            formatter.applyPattern(matcher.group(1));
            return formatter.format(new Date(timestamp));
        } else {
            return super._GetValue(_name);
        }
    }
}
